package com.tgy.基础学习.Thread.Synchronized;

import lombok.SneakyThrows;

/**
 * @author 送你一块二向箔
 * @date 2021/11/08 17:41
 */
public class DeadLock {
    public static void main(String[] args) {
        Thread 小A = new Thread(new Makeup(0, "小A"), "线程一");
        Thread 小B = new Thread(new Makeup(1, "小B"), "线程二");
        小A.start();
        小B.start();

    }
}

class Lipstick {

}

class Mirror {

}

class Makeup implements Runnable {

    //只有一份资源
    static Lipstick lipstick = new Lipstick();
    static Mirror mirror = new Mirror();

    //选择和名字
    int choice;
    String name;

    //构造器
    public Makeup(int choice, String name) {
        this.choice = choice;
        this.name = name;
    }

    @SneakyThrows
    @Override
    public void run() {
        makeup();
    }

    private void makeup() throws InterruptedException {

        /**
         * 死锁情况
         */
        if (choice == 0){
            synchronized (lipstick) {//获得口红的锁
                System.out.println(Thread.currentThread().getName() +"获得口红的锁");
                Thread.sleep(1000);
                synchronized (mirror) {//获得镜子的锁
                    System.out.println(Thread.currentThread().getName() +"获得镜子的锁");
                    Thread.sleep(1000);
                }
            }
        }else {
            synchronized (mirror) {//获得口红的锁
                System.out.println(Thread.currentThread().getName() +"获得口红的锁");
                Thread.sleep(2000);
                synchronized (lipstick) {//获得镜子的锁
                    System.out.println(Thread.currentThread().getName() +"获得镜子的锁");
                    Thread.sleep(1000);
                }
            }
        }


        /**
         * 非死锁
         */

/*        if (choice == 0) {
            synchronized (lipstick) {//获得口红的锁
                System.out.println(Thread.currentThread().getName() + "获得口红的锁");
                Thread.sleep(1000);
            }
            synchronized (mirror) {//获得口红的锁
                System.out.println(Thread.currentThread().getName() + "获得镜子的锁");
                Thread.sleep(1000);
            }
        } else {
            synchronized (mirror) {//获得口红的锁
                System.out.println(Thread.currentThread().getName() + "获得镜子的锁");
                Thread.sleep(2000);
            }
            synchronized (lipstick) {//获得口红的锁
                System.out.println(Thread.currentThread().getName() + "获得口红的锁");
                Thread.sleep(1000);
            }
        }*/

    }
}

